<?php
namespace common\services;

use common\models\System;
use yii\data\Pagination;

class SystemServices extends System
{

    /**
     * @param $code
     * @param bool $withSession
     * @return array|mixed|\yii\db\ActiveRecord[]
     */
    public function getSys($code = null, $withSession = true){
        $sessKey = "system_list";
        $result = \Yii::$app->cache->get($sessKey);
        if ($withSession && !empty($result)){
            if (!empty($code)){
                if (!isset($result['code'])){
                    $find = System::findOne(['code' => $code, 'status' => self::STATUS_FLAG_NORMAL]);
                    if (!empty($find)) {
                        $result[$code] = array(
                            'id' => $find->id,
                            'name' => $find->name,
                            'code' => $find->code,
                            'value' => $find->value,
                        );
                        \Yii::$app->cache->set($sessKey, $result);
                    }else{
                        $result[$code] = '';
                    }
                }
                return $result[$code];
            } else {
                return $result;
            }
        } else {
            $result = System::find()->andFilterWhere(['status' => self::STATUS_FLAG_NORMAL])->indexBy('code')->select('id,name,code,value')->asArray()->orderBy('order desc,id desc')->all();
            if ( $withSession ){
                \Yii::$app->cache->set($sessKey, $result);
            }
            if (!empty($code)){
                return isset($result[$code]) ? $result[$code] : '';
            } else {
                return $result;
            }
        }
    }

}
